<?php

namespace app\ports\controller\publics;

use app\ports\constants\FilesConstants;
use think\Config;
use think\Db;

/**
 * 数据SQL
 * Class
 * @package
 */
class DataSql
{
	/**
	 * 对象实例
	 * @var object
	 */
	protected static $instance;

	protected $table = "";

	protected $prefix = "";
	/**
	 * 类架构函数
	 */
	public function __construct()
	{
		 
	}

	/**
	 * 获取实例对象
	 * @return DataSql|object
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 交易-存储
	 * @param        $option     array 存储参数
	 * @param  $tp 存储表类型 [T 交易存储 S 达标 B 分红]  
	 * @return bool              
	 */
	public function transSave($table, $option = [])
	{
		try {
			$where = $this->check_condition_format($option, FilesConstants::TRAN_STORE_WHERE_FIELDS);
			if ($where) {
				$check = $this->checkStore($table,$where);
				if ($check) {
					$update = $this->update_nums_format($option, FilesConstants::TRAN_STORE_UPDATE_FIELDS);
					Db::name($table)->where($where)->update($update);
				} else {
					$data = $this->_process_storage_fields($option, FilesConstants::TRAN_STORE_ADDS_FIELDS);
					Db::name($table)->insert($data);
				}
			}
		} catch (\Exception $e) {
		}
	}

	/**
	 * 检测存在
	 * @return string
	 */
	protected function checkStore($table,$where)
	{
		$check = false;
		try {
			$con = Db::name($table)->where($where)->count();
			$con && $check = true;
		} catch (\Exception $e) {
		}
		return $check;
	}


	/**
	 * 处理存储字段
	 * @param array $option  处理数组
	 * @param string $str  可须字段
	 * @return bool|array
	 */
	public function _process_storage_fields($option = [], $str = "")
	{
		if (!empty($option) && is_string($str)) {
			$return = [];
			if (!empty($option) && !empty($str)) {
				$ex = explode(",", $str);
				for ($i = 0; $i < count($ex); $i++) {
					if (!empty($option[$ex[$i]])) {
						$return[$ex[$i]] = $option[$ex[$i]];
					}
				}
			}
			return $return;
		}
		return false;
	}

	/**
	 * 数字更新-格式
	 * @param parms[更新数据]|update[更新字段]
	 * @return array
	 */
	private function update_nums_format($option = [], $str = "")
	{
		$up = [];
		if (is_array($option) && is_string($str)) {
			$ex = explode(",", $str);
			if (!empty($option) && !empty($str)) {
				for ($i = 0; $i < count($ex); $i++) {
					$up[$ex[$i]] = Db::raw($ex[$i] . " + " . $option[$ex[$i]]);
				}
			}
		}
		return $up;
	}

	/**
	 * 条件
	 * @return string
	 */
	protected function check_condition_format($option = [], $str = "")
	{
		$return = "";
		if (is_array($option) && is_string($str)) {
			if (!empty($option) && !empty($str)) {
				$ex = explode(",", $str);
				for ($i = 0; $i < count($ex); $i++) {
					if (isset($option[$ex[$i]])) {
						$return .= $ex[$i] . " = '" . $option[$ex[$i]] . "' and ";
					}
				}
			}
		}
		return rtrim($return, " and ");
	}
}
